<template>
	<view class="container qj-bg-color bg-image relative">
		<view class="flex flex-col items-start absolute content">

			<!-- #ifdef MP-WEIXIN -->
			<view v-if="!showPhone" class="" @tap.stop="tapLoginWx">
				<image src="../../static/image/login_btn_yes.png" class="btn" mode="scaleToFill" />
			</view>
			<button class="" @tap="openBack">
				<text>暂不登录</text>
			</button>
			<!-- #endif -->
			
			<!-- #ifdef APP-PLUS -->
			<view class="uiwu-button uiwu-flex-center m-auto" @tap.stop="tapLogin">
				<image src="@/static/image/wx.png" mode="widthFix" class="wx-image"></image>
				<text>微信登录</text>
			</view>
			<!-- #endif -->
			
			<!-- <view class="mt-2 flex items-center justify-center w-full"  v-if="is_ios"  @click="appleLoginFun">
				<image src="@/static/image/apple.png" mode="widthFix" class="apply-image"></image>
				<text>Apple登录</text>
			</view> -->
			

			<!-- #ifdef WEB -->
			<view v-if="!showPhone" class=" flex items-center justify-center w-full" @tap.stop="tapLoginWxWeb">
				<!-- <image src="/static/wx.png" mode="widthFix"></image> -->
				<image src="../../static/image/login_btn_yes.png" class="btn" mode="scaleToFill" />
			</view>
			<!-- #endif -->

			<view class="flex justify-center items-center text-black text-sm mt-2">
				<radio style="transform: scale(0.8);" color="#EF821E" :checked="isRadio" @tap="isRadio = !isRadio" />
				登录即表明同意 <navigator url="/pages/login/agreement" class=" text-white">用户协议</navigator> 和 <navigator
					class=" text-white" url="/pages/login/privacy">
					隐私政策</navigator>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { spreadUid, token as tokenOperate, userSn } from '@/api/common';
import { appleLogin, userInfo, wechatAuth, wechatConfig, wxLoain, wxmpLoain } from '@/api/interface/interface';
import { ref } from 'vue';
import Gap from "@/components/gap.vue";
import { uiwu } from '@/api/interface/interface';
import { onLoad } from '@dcloudio/uni-app';
const loginInfo = ref(null);
const showPhone = ref(false);
const wechatCode = ref("");
const is_ios = ref(false);
const isRadio = ref<boolean>(false);

const tapLoginWx = () => {
	let spread_uid = spreadUid();
	console.log("tapLoginWx");
	uni.login({
		provider: 'weixin',
		success: async (res): Promise<any> => {
			const data = {
				code: res.code,
				spread_uid: spread_uid
			}
			uni.showLoading({
				title: '登录中'
			})
			let result = await wxmpLoain(data);
			if (!result.data?.isbind) {
				showPhone.value = true
				loginInfo.value = result.data
			} else {
				handleResult(result)
			}

		},
		fail: (err) => {
			uiwu.model({
				title: '登录失败',
				content: JSON.stringify(err)
			})
		}
	})
}

/**
 * tapLogin App微信登录
 */
const tapLogin = (): void => {
	if (!isRadio.value) return uiwu.toast('请先勾选允许用户协议和隐私政策')
	uni.login({
		provider: 'weixin',
		success: async ({ authResult: { unionid, openid } } : { authResult : { unionid : string, openid : string } }) : Promise<any> => {
			const { userInfo: { nickName, avatarUrl } } = await getUserInfo()//获取微信基本信息
			const result = await wxLoain({
				nickname: nickName,
				unionid,
				avatar: avatarUrl,
				openid
			})
			handleResult(result)
		},
		fail: (err) => {
			console.log('err123==', err)
			uiwu.model({
				title: '登录失败',
				content: JSON.stringify(err)
			})
		}
	})
}

/**
 * getUserInfo 获取微信用户的基本信息
 */
const getUserInfo = (): Promise<object> => {
	return new Promise((resolve, reject) => {
		uni.getUserInfo({
			provider: 'weixin',
			success: (res: object) => {
				resolve(res)
			},
			fail: (err) => {
				console.log('er123r', err)
				reject(err)
			}
		})
	})
}

const tapLoginWxWeb = async () => {
	if (!isRadio.value) return uiwu.toast('请先勾选允许用户协议和隐私政策');
	let spread_uid = spreadUid();
	const result = await wechatAuth({
		spread_uid,
		code: wechatCode.value
	});
	if (result.status == 200) {
		handleResult(result);
	}

}

const getCode = async () => {
	uni.showLoading({
		title: "加载中..."
	})
	if (location.href.indexOf("code") > -1) {

		let paramStr = location.href.split("?")[1];
		if (paramStr.indexOf("code") > -1) {
			let array = paramStr.split("&");
			let object: any = {};
			array.forEach((x: string) => {
				const a = x.split("=");
				object[a[0]] = a[1];
			});
			wechatCode.value = object.code;
			uni.hideLoading();
			return object;
		}
	} else {
		const config = await wechatConfig();
		if (config.status == 200) {
			location.href = config.data.oauth_url;
		}
	}
	return {};
}

// apple登录
const appleLoginFun = () => {
	//if (!isRadio.value) return uiwu.toast('请先勾选允许用户协议和隐私政策')
	uni.login({
		provider: "apple",
		success: (e) => {
			uni.showLoading({
				title: '登录中...',
				mask: true
			});
			uni.getUserInfo({
				provider: 'apple',
				success: async ({ userInfo: { openId, identityToken, fullName: { familyName, givenName } } }: any) => {
					const result = await appleLogin({
						identity_token: identityToken,
						apple_user_id: openId,
						nickname: `${familyName}${givenName}`
					})
					handleResult(result)
				}
			})
		},
		fail: (err) => {
			this.uiwu.toast(JSON.stringify('登录取消'))
		}
	})
}

const handleResult = ({ data: { isbind, token, cache_key, userInfo: { is_first_login, uid } } }) => {
	uiwu.hideloading()

	// #ifdef WEB
	let currentUrl = window.location.href;
	let baseUrl = currentUrl.split('?')[0].replace(/\/$/, '');
	// #endif
	if (!isbind) {

		// #ifdef WEB
		location.href = baseUrl + `/#/pages/user/binding?cache_key=${cache_key}`;
		return;
		// #endif

		uni.navigateTo({
			url: `/pages/user/binding?cache_key=${cache_key}`
		})
		return
	}
	tokenOperate(token);
	userSn(uid);
	uiwu.toast('登录成功');
	if (is_first_login) {

		// #ifdef WEB
		location.href = baseUrl + "/#/pages/login/invite";
		return;
		// #endif
		
		uni.redirectTo({
			url: '/pages/login/invite'
		})
		return
	}
	setTimeout(() => {
		// #ifdef WEB
		location.href = baseUrl + "/#/pages/index/index";
		return;
		// #endif
		uni.navigateTo({
			url: '/pages/index/index?'
		})
	}, 400)
}

const openBack = () => {
	uni.navigateTo({
		url: "/pages/index/index"
	});
}

onLoad(() => {
	// #ifdef WEB
	getCode();
	// #endif
	is_ios.value = uni.getSystemInfoSync().platform == 'ios' ? true : false;
});
</script>

<style lang="scss" scoped>
.container {
	background-image: url('../../static/image/login_bg.png');
	height: 100vh;
	width: 100vw;

	.content {
		top: 80%;
	}

	.btn {
		width: 220px;
		height: 45px;
	}
}

.wx-image {
	width: 60rpx;
	height: 60rpx;
}
.apply-image {
	width: 60rpx;
	height: 60rpx;
}
</style>
